package client;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;

import dataContracts.FileState;
import dataContracts.InstallSettings;

import util.ChecksumHelper;
import util.SHAHelper;
import util.SerializationHelper;

import dataContracts.SharedDirectory;

public class ClientDirectory extends SharedDirectory {
	transient SerializationHelper<ClientDirectory> _serializer;
	String settingsFileName = ".lanyard";
	File settingsFile;
	public InstallSettings config; 
	
	public ClientDirectory(String directoryPath) {
		super(directoryPath);
		
		config = InstallSettings.getSettings();
		
		_serializer = new SerializationHelper<ClientDirectory>();
		settingsFile = new File(this.getFilePath() + File.separator + settingsFileName);
		
		/*if (IsConfigured()) {
			refresh();
			System.out.println("loaded from config object");
		} else {*/
			Install();
			System.out.println("loaded from scratch");
//		}
		
	}
	
	// check for already configured directory...
	public boolean IsConfigured() {
		return settingsFile.exists();
	}
	
	public void refresh() {
		if (directory.isDirectory()) {
	    	for (File f : directory.listFiles()) {
	    		if (!f.isHidden()) {
	    			ClientFile cf = findFile(f.getName());
	    			if (cf == null) {
	    				// new file
	    				this.addFile(f.getName());
	    			} else {
	    				cf.refresh();
	    			}
	    		}
			}
    	}
		
		setChecksum(ChecksumHelper.GetChecksum(directory));
	}
	
	public void Install() {
		// load from scratch
		files.clear();
		
		if (directory.isDirectory()) {
	    	for (File f : directory.listFiles()) {
	    		if (!f.isHidden()) {
	    			ClientFile cf = new ClientFile(f);
	    			cf.refresh();
	    			this.files.add(cf);
	    		}
			}
    	}
		
		setChecksum(ChecksumHelper.GetChecksum(directory));
		
		// save state for future use
		Serialize();
	}
	
	public void UnInstall() {
		settingsFile.delete();
	}
	
	public boolean hasLocalChanges() {
		for (ClientFile f : this.files) {
			if (f.fileState != FileState.Synchronized)
				return true;
		}
		
		return false;
	}
	
	public void addFile(ClientFile file) {
		file.fileState = FileState.Added;
		files.add(file);
	}
	
	public void addFile(String fileName) {
		addFile(findOrCreateFile(fileName));
	}
	
	public void removeFile(String path) {
		ClientFile f = findFile(path);
		
		if (f != null) {
			files.remove(f);
		}
		
		f.getFileReference().delete();
	}
	
	public ClientFile findFile(String path) {
		for (ClientFile f : this.files) {
			if (f.getName().equals(path)) {
				return f;
			}
		}
		
		return null;
	}
	
	public ClientFile findOrCreateFile(String path) {
		ClientFile cf = findFile(path);
		
		if (cf == null) {
			cf = new ClientFile(new File(config.directoryPath + File.separator + path));
		}
		
		return cf;
	}
	
	public void Serialize() {
		_serializer.Serialize(this, settingsFile);
	}
	
	public ClientDirectory Deserialize() {
		return (ClientDirectory) _serializer.Deserialize(settingsFile);
	}
}
